import React, { Component } from 'react';
import moment from 'moment';
import { Form, Input, Button, PageHeader, message, Col, Row, Upload, DatePicker, TreeSelect, Select } from 'antd';
import { CaretDownOutlined, AppstoreTwoTone, } from '@ant-design/icons';
import { connect, } from 'dva';
import styles from './common.less'
import * as requesturl from "@/services/request-url";

const { TextArea } = Input
const { Option } = Select

function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }
@connect((global) => ({
    userInfo: global.userInfo,
}))
class CreateStandardForm extends Component {
    constructor(props) {
        super(props);
        this.state = {
            form: {},
            releaseTime: "",
            endTime: "",
            effectDate: "",
            loading: false,
            formloading: false,
            defaultfilelist: [],//文件列表
            standardTypeList: [

            ],
            standardTypeList1: [

            ],
            subjectList: [

            ],
            fileList:[],
            logo:""
        }
    }

    componentDidMount = () => {
        this.getScienceTypeList()
        this.getStandardTypeList()
        this.getStandardTypeList1()

        console.log(this.props)
        const { standardDetail } = this.props
        standardDetail.endTime = standardDetail.endTime ? moment(standardDetail.endTime) : ""
        standardDetail.releaseTime = standardDetail.releaseTime ? moment(standardDetail.releaseTime) : ""
        standardDetail.effectDate = standardDetail.effectDate ? moment(standardDetail.effectDate) : ""
        if (standardDetail.fileUrl) {//处理文件回显
            let fileurllist = []
            standardDetail.fileUrl.split(",").map((item, index) => {
                let itemarr = item.split("/")
                let obj = {
                    uid: index * -40,
                    name: itemarr[itemarr.length - 1],
                    status: 'done',
                    url: item,
                }
                fileurllist.push(obj)
            })
            this.setState({
                defaultfilelist: fileurllist
            })
        }
        if(standardDetail.logo){
            let fileurllist = []
            standardDetail.logo.split(",").map((item, index) => {
                let itemarr = item.split("/")
                let obj = {
                    uid: index * -40,
                    name: itemarr[itemarr.length - 1],
                    status: 'done',
                    url: item,
                }
                fileurllist.push(obj)
            })
            this.setState({
                fileList: fileurllist
            })
        }
        this.setState({
            form: {
                ...standardDetail
            },
            effectDate: standardDetail.effectDate,
            endTime: standardDetail.endTime,
            releaseTime: standardDetail.releaseTime,
            formloading: true,
        })
    }
    //获取标准类别
    getStandardTypeList = () => {
        this.props.dispatch({
            type: "global/getByType",
            payload: {
                type: "STANDARDTYPE"
            }
        }).then(res => {
            console.log(res)
            if (res) {
                this.setState({
                    standardTypeList: res.data
                })
            }
        })
    }
    //获取标准类别
    getStandardTypeList1 = () => {
        this.props.dispatch({
            type: "global/getByType",
            payload: {
                type: "BEHAVIOUR"
            }
        }).then(res => {
            console.log(res.data)
            if (res) {
                this.setState({
                    standardTypeList1: res.data
                })
            }
        })
    }
    //获取学科分类
    getScienceTypeList = () => {
        this.props.dispatch({
            type: "global/queryCategory",
            payload: {
                pid: 2
            }
        }).then(res => {
            console.log(res)
            if (res) {
                res.data.map(item => {
                    item.value = item.dicCode
                    item.title = item.dicName
                    item.disabled = true
                    if (item.childList.length > 0) {
                        item.children = item.childList
                        item.children.map(item2 => {
                            item2.value = item2.dicCode
                            item2.title = item2.dicName
                        })
                    }
                })
                this.setState({
                    subjectList: res.data
                }, () => { console.log(this.state.subjectList) })
            }
        })
    }
    //校验通过提交
    submit = (value) => {
        let { form, releaseTime, endTime, effectDate, defaultfilelist,logo } = this.state
        console.log('hurui values', value)
        console.log(releaseTime, endTime, effectDate)
        let fileUrls = []
        defaultfilelist.map((item, index) => {
            fileUrls.push(item.url)
        })
        console.log(form)
        this.props.dispatch({
            type: "global/createStandard",
            payload: {
                ...form,
                releaseTime,
                effectDate,
                endTime,
                fileUrl: fileUrls.join(","),
                id: this.props.standardDetail.id,
                logo:logo
            }
        }).then(res => {
            if (res) {
                message.success("更新成功！")
                this.props.getStandardList()
                this.props.handleOk()
            }
        })

    }

    //校验失败
    onFinishFailed = (err) => {
        message.warning("请填写完整！")
    }

    handleCancel = () => {
        this.props.handleCancel()
    }
    //表单字段改变
    handleValuesChange = (changedValues, allValues) => {
        this.setState({
            form: allValues,
        })
    }
    //上传附件
    handleFileUpload = ({ file, fileList }) => {
        if (file.response && file.response.code === "403") {
            let a = document.createElement("a")
            a.href = `${requesturl.login}/cas/jwt/login.do`;
            a.click();
        }
        if (file.status !== 'uploading') {
            console.log(file.response, fileList);
        }
        if (file.status === 'done' && file.response.code === "1") {
            this.setState({
                defaultfilelist: [
                    {
                        uid: new Date(),
                        name: '附件',
                        status: 'done',
                    },
                ]
            })
            message.success("上传成功！")
        }
        else if (file.status === 'removed') {
            console.log(fileList)
            this.setState({
                defaultfilelist: fileList
            }, () => console.log(this.state.defaultfilelist))
        }
        if (file.status === 'done' && file.response.code === "0") {
            this.setState({
                defaultfilelist: [
                    {
                        uid: new Date(),
                        name: '错误文件',
                        status: 'error',
                    },
                ]
            })
            message.error("不允许上传此类型文件！")
        }
    }
    //logo
    handleChangeImg = ({ file, fileList }) => {
        if(file.response&&file.response.code==="403"){
          let a = document.createElement("a")
          a.href = `${requesturl.login}/cas/jwt/login.do`;
          a.click();
      }
        console.log(file, file.status)
        console.log(fileList)
        if (file.status === "done") {
          console.log(fileList)
          this.setState({
            logo: file.response.data
          })
    
        } else if (file.status === "removed") {
          console.log(fileList, file)
          this.setState({
            logo: ""
          })
        }
        this.setState({ fileList })
      };
      //点击图片
      handlePreview = async file => {
        console.log(file)
        if (!file.url && !file.preview) {
          file.preview = await getBase64(file.originFileObj);
        }
    
        this.setState({
          previewImage: file.url || file.preview,
          previewVisible: true,
          previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
      };
    //标准类型改变
    standardTypeChange = (value) => {
        console.log(value)
        this.setState({
            form: {
                ...this.state.form,
                type: value
            }
        })
    }
    //标准规范改变
    standardTypeChange1 = (value) => {
        console.log(value)
        this.setState({
            form: {
                ...this.state.form,
                standardType: value
            }
        })
    }
    //学科选择
    scienceChange = (value) => {
        console.log(value)
        this.setState({
            form: {
                ...this.state.form,
                subject: value
            }
        })
    }
    render() {
        let { form, loading,fileList } = this.state;
        const { modalTitle } = this.props;

        const routes = [
            { breadcrumbName: '标准管理规范', },
            { breadcrumbName: '标准信息录入', },
        ]

        return (
            <div className={styles.all}>
                {
                    modalTitle !== "标准编辑" ?
                        <div className={styles.pagetop}>
                            <span className={styles.pageheadericon}>
                                <AppstoreTwoTone />
                            </span>
                            <span className={styles.pageheader}>
                                <PageHeader
                                    backIcon="true"
                                    breadcrumb={{ routes }}
                                    onBack={() => window.history.back()}
                                />
                            </span>
                        </div> : ""
                }

                <div className={styles.form}>
                    {
                        this.state.formloading ?
                            <Form
                                name="form"
                                autoComplete="off"
                                labelAlign="right"
                                // onFinish={ this.submit(value) }
                                onFinish={this.submit}
                                onFinishFailed={this.onFinishFailed}
                                initialValues={form}
                                // scrollToFirstError={ true }
                                onValuesChange={this.handleValuesChange}
                            >
                                <div style={{ background: "#F2F2F2", padding: "20px" }}>
                                    <div style={{ background: "white" }}>
                                        <div style={{ height: "8px" }}></div>
                                        <div className={styles.formChildText}><CaretDownOutlined />标准基础信息</div>
                                        <div className={styles.formItem}>
                                            <Row gutter={100}>
                                                <Col span={8}>
                                                    <Form.Item name="tile" label="标题"
                                                        rules={[{ required: true, message: '请填写标题', },]}>
                                                        <Input placeholder="请输入标题" value={form.tile} />
                                                    </Form.Item>
                                                    <Form.Item name="num" label="标准号"
                                                        rules={[{ required: true, message: '请填写标准号', },]}>
                                                        <Input placeholder="请输入标准号" value={form.num} />
                                                    </Form.Item>
                                                    <Form.Item name="releaseTime" label="发布日期"
                                                        rules={[{ required: true, message: '请填写发布日期', },]}>
                                                        <DatePicker placeholder="请输入发布日期"
                                                            style={{ width: "100%" }}
                                                            onChange={(date, dateString) => { this.setState({ releaseTime: dateString }) }} />
                                                    </Form.Item>
                                                    <Form.Item name="unit" label="归口单位"
                                                        rules={[{ required: true, message: '请填写归口单位', },]}>
                                                        <Input placeholder="请输入归口单位" value={form.unit} />
                                                    </Form.Item>
                                                    <Form.Item label="logo">
                                                        <Upload
                                                            name="file"
                                                            listType="picture-card"
                                                            multiple={true}
                                                            fileList={fileList}
                                                            headers={{ 'p-user-token': sessionStorage.getItem("token") }}
                                                            action={`http://${window.location.host}/api/jyk/file/upload`}
                                                            onPreview={this.handlePreview}
                                                            onChange={this.handleChangeImg}
                                                        >
                                                            {
                                                                fileList.length > 0 ? null : <div>+</div>
                                                            }
                                                        </Upload>
                                                    </Form.Item>

                                                </Col>
                                                <Col span={8}>
                                                    <Form.Item name="subtitle" label="副标题"
                                                        rules={[{ required: true, message: '请填写副标题', },]}>
                                                        <Input placeholder="请输入副标题" value={form.subtitle} />
                                                    </Form.Item>
                                                    <Form.Item name="type" label="标准类别"
                                                        rules={[{ required: true, message: '请填写标准类别', },]}>
                                                        <Select defaultValue={form.type} placeholder="请选择标准类别" onChange={this.standardTypeChange}>
                                                            {
                                                                this.state.standardTypeList.map((item, index) => {
                                                                    return <Option key={index} value={item.dicCode}>{item.dicName}</Option>
                                                                })
                                                            }
                                                        </Select>

                                                    </Form.Item>
                                                    <Form.Item name="effectDate" label="实施日期"
                                                        rules={[{ required: true, message: '请填写实施日期', },]}>
                                                        <DatePicker placeholder="请输入实施日期"
                                                            style={{ width: "100%" }}
                                                            onChange={(date, dateString) => { this.setState({ effectDate: dateString }) }} />
                                                    </Form.Item>

                                                    <Form.Item name="deft" label="主管部门"
                                                        rules={[{ required: true, message: '请填写主管部门', },]}>
                                                        <Input placeholder="请输入主管部门" value={form.deft} />
                                                    </Form.Item>
                                                </Col>
                                                <Col span={8}>
                                                    <Form.Item name="executeUnit" label="执行单位"
                                                        rules={[{ required: true, message: '请填写执行单位', },]}>
                                                        <Input placeholder="请输入执行单位" value={form.executeUnit} />
                                                    </Form.Item>
                                                    <Form.Item name="subject" label="所属学科"
                                                        rules={[{ required: true, message: '请填写所属学科', },]}>
                                                        <TreeSelect treeDefaultExpandAll placeholder="请选择学科" value={form.subject} treeData={this.state.subjectList} onChange={this.scienceChange} />
                                                    </Form.Item>
                                                    <Form.Item name="endTime" label="结束日期"
                                                        rules={[{ required: true, message: '请填写结束日期', },]}>
                                                        <DatePicker placeholder="请输入结束日期"
                                                            style={{ width: "100%" }}
                                                            onChange={(date, dateString) => { this.setState({ endTime: dateString }) }} />
                                                    </Form.Item>
                                                    <Form.Item name="standardType" label="标准规范"
                                                        rules={[{ required: true, message: '请填写标准规范', },]}>
                                                        <Select defaultValue={form.standardType} placeholder="请选择标准规范" onChange={this.standardTypeChange1}>
                                                            {
                                                                this.state.standardTypeList1.map((item, index) => {
                                                                    return <Option key={index} value={item.dicCode}>{item.dicName}</Option>
                                                                })
                                                            }
                                                        </Select>

                                                    </Form.Item>
                                                    <Form.Item label="上传标准附件">
                                                        <Upload maxCount={1} headers={{ 'p-user-token': sessionStorage.getItem("token") }} action={`http://${window.location.host}/api/jyk/file/upload`} onChange={this.handleFileUpload} defaultFileList={this.state.defaultfilelist}>
                                                            <Button type="primary" style={{ width: "100%" }}>上传附件</Button>
                                                            {
                                                                this.state.defaultfilelist.length === 0 ? "暂无文件" : null
                                                            }
                                                        </Upload>
                                                    </Form.Item>
                                                    
                                                </Col>
                                            </Row>
                                        </div>
                                    </div>
                                    <div style={{ marginTop: "10px", background: "white" }}>
                                        <div style={{ height: "8px" }}></div>
                                        <div className={styles.formChildText}><CaretDownOutlined />分类号</div>
                                        <div className={styles.formItem}>
                                            <Row gutter={200}>
                                                <Col span={11}>
                                                    <Form.Item name="chinaTypeNum" label="中国标准分类号"
                                                        rules={[{ required: true, message: '请输入中国标准分类号', },]}>
                                                        <Input placeholder="请输入中国标准分类号" value={form.chinaTypeNum} />
                                                    </Form.Item>
                                                </Col>
                                                <Col span={11}>
                                                    <Form.Item name="nationalTypeNum" label="国际标准分类号"
                                                        rules={[{ required: true, message: '请输入国际标准分类号', },]}>
                                                        <Input placeholder="请输入国际标准分类号" value={form.nationalTypeNum} />
                                                    </Form.Item>
                                                </Col>
                                            </Row>
                                        </div>
                                    </div>
                                    <div style={{ marginTop: "10px", background: "white" }}>
                                        <div style={{ height: "8px" }}></div>
                                        <div className={styles.formChildText}><CaretDownOutlined />标准简介</div>
                                        <div className={styles.formItem}>
                                            <Row>
                                                <Col span={22}>
                                                    <Form.Item name="content" label="摘要内容"
                                                        rules={[{ required: true, message: '请输入摘要内容', },]}>
                                                        <TextArea placeholder="请输入摘要内容" rows={5} value={form.content} />
                                                    </Form.Item>
                                                </Col>
                                            </Row>
                                        </div>
                                    </div>
                                    <div style={{ marginTop: "10px", background: "white" }}>
                                        <div style={{ height: "8px" }}></div>
                                        <div className={styles.formChildText}><CaretDownOutlined />起草单位</div>
                                        <div className={styles.formItem}>
                                            <Row gutter={200}>
                                                <Col span={11}>
                                                    <Form.Item name="writeUnit" label="单位名称"
                                                        rules={[{ required: true, message: '请填写单位名称', },]}>
                                                        <TextArea placeholder="请输入单位名称" rows={3} value={form.writeUnit} />
                                                    </Form.Item>
                                                </Col>
                                                <Col span={11}>
                                                    <Form.Item name="writeSchool" label="学校名称"
                                                        rules={[{ required: true, message: '请填写学校名称', },]}>
                                                        <TextArea placeholder="请输入学校名称" rows={3} value={form.writeSchool} />
                                                    </Form.Item>
                                                </Col>
                                            </Row>
                                        </div>
                                    </div>
                                    <div style={{ marginTop: "10px", background: "white" }}>
                                        <div style={{ height: "8px" }}></div>
                                        <div className={styles.formChildText}><CaretDownOutlined />起草人</div>
                                        <div className={styles.formItem}>
                                            <Col span={8}>
                                                <Form.Item name="author" label="姓名">
                                                    <Input placeholder="请输入姓名" value={form.author} />
                                                </Form.Item>
                                            </Col>
                                        </div>
                                    </div>
                                    <div style={{ textAlign: "center", marginTop: "20px" }}>
                                        {
                                            modalTitle === "标准编辑" ?
                                                <div>
                                                    <Button onClick={this.handleCancel} style={{ marginRight: "20px" }}>取消</Button>
                                                    <Button type="primary" htmlType="submit" loading={loading}>保存</Button>
                                                </div>
                                                :
                                                // <Button type="primary" htmlType="submit" loading={ loading }>确定录入</Button>
                                                <div>
                                                    <Button onClick={this.handleCancel} style={{ marginRight: "20px" }}>取消</Button>
                                                    <Button type="primary" htmlType="submit" loading={loading}>保存</Button>
                                                </div>
                                        }
                                    </div>
                                </div>
                            </Form> : ""
                    }
                </div>
            </div>
        );
    }
}

export default CreateStandardForm;